import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

// 消息弹框
import 'package:fluttertoast/fluttertoast.dart';

// 中国的城市三级联动选择器
import 'package:city_pickers/city_pickers.dart';

import '../../services/EventBus.dart';
import '../../services/ScreenAdapter.dart';
import '../../widget/MyTextField.dart';
import '../../widget/MyButton.dart';
import '../../services/SignServices.dart';
import '../../services/UserInfo.dart';
import '../../config/Config.dart';

// 编辑收货地址页面
class AddressEditPage extends StatefulWidget {
  final Map arguments;

  AddressEditPage({this.arguments});

  @override
  State<StatefulWidget> createState() =>
      AddressEditState(addressInfo: this.arguments['addressInfo']);
}

class AddressEditState extends State {
  Map addressInfo;
  List newListAddress = [];

  AddressEditState({this.addressInfo});

  @override
  void initState() {
    super.initState();

    // 以空格切割地址
    _splitAddress();
  }

  // 以空格切割地址
  _splitAddress() {
    String tempAddress = addressInfo['address'];
    List res = tempAddress.split(' ');

    this.setState(() {
      this.newListAddress = res;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('编辑收货地址')),
      body: ListView(
        children: [
          // 姓名
          MyTextField(
            text: addressInfo['name'],
            height: ScreenAdapter.height(120),
            cb: (value){
              this.setState(() {
                this.addressInfo['name'] = value;
              });
            },
          ),

          // 电话
          MyTextField(
            text: addressInfo['phone'],
            height: ScreenAdapter.height(120),
            cb: (value){
              this.addressInfo['phone'] = value;
            },
          ),

          // 选择省、市、县
          ListTile(
            title: Row(
              children: [
                Icon(Icons.add_location, color: Colors.black54),
                Text(
                  '${newListAddress[0]}',
                  style: TextStyle(fontSize: 14, color: Colors.black54),
                ),
              ],
            ),
            onTap: _showAddressMenu,
          ),
          Divider(),

          // 详细地址
          TextField(
            maxLines: 3,
            decoration: InputDecoration(
                border: InputBorder.none,
                contentPadding: EdgeInsets.all(14),
                hintText: '${newListAddress[1]}',
                hintStyle: TextStyle(fontSize: 14)),
            onChanged: (value) {
              this.setState(() {
                this.newListAddress[1] = value;
              });
            },
          ),
          Divider(color: Colors.black26),
          SizedBox(height: 50),

          // 保存
          MyButton(
            text: '保存修改',
            color: Colors.red,
            leftMargin: 50,
            rightMargin: 50,
            height: ScreenAdapter.height(160),
            cb: _saveAddress,
          )
        ],
      ),
    );
  }

  // 保存地址
  _saveAddress() async {
    // 如果用户输入了全部信息
    if (this._judgeAllInfo()){
      var userInfo = await UserInfoServices.getUserInfo();
      var tempJson = {
        "uid": addressInfo['uid'],
        "id": addressInfo['_id'],
        "name": addressInfo['name'],
        "phone": addressInfo['phone'],
        "address": '${newListAddress[0]} ${newListAddress[1]}',
        "salt": userInfo[0]['salt'],
      };

      var sign = SignServices.getSign(tempJson);

      var api = Config.domain + 'api/editAddress';
      var response = await Dio().post(api, data: {
        "uid": addressInfo['uid'],
        "id": addressInfo['_id'],
        "name": addressInfo['name'],
        "phone": addressInfo['phone'],
        "address": '${newListAddress[0]} ${newListAddress[1]}',
        "sign": sign
      });

      var res = response.data;
      if(res['success']){
        // 弹框提示
        Fluttertoast.showToast(
          msg: "地址修改成功！",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
        eventBus.fire(new AddressListUploadEvent('AddressList页面刷新'));

        Navigator.pop(context);
      }else {
        // 弹框提示
        Fluttertoast.showToast(
          msg: "地址修改失败！",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
      }

    }
  }

  // 判断用户是否输入、选择所有信息
  _judgeAllInfo(){
    if(this.addressInfo['name'] == ''){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "用户名不能为空！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
      return false;

    } else if (this.addressInfo['phone'] == ''){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "电话不能为空！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
      return false;

    } else if (this.newListAddress[1] == ''){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "详细地址不能为空！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
      return false;
    }
    return true;
  }

  // 底部弹出地址选择框
  _showAddressMenu() async {
    // 呼出弹出层,显示多级选择器
    Result result = await CityPickers.showCityPicker(
      context: context,
      cancelWidget: Text('取消'),
      confirmWidget: Text('确定'),
    );

    if (result != null) {
      this.setState(() {
        this.newListAddress[0] =
            '${result.provinceName}/${result.cityName}/${result.areaName}';
      });
    }
  }
}
